#include"queue.h"

void QInit(Queue* q)
{
	assert(q);
	q->size = 0;
	q->head = q->tail = (QNode*)malloc(sizeof(QNode));
	if (q->head == NULL)
	{
		perror("malloc error");
	}
	q->head->data = 0;
	q->tail->next = NULL;
}

void QDestroy(Queue* q)
{
	while (q->head != NULL)
	{
		QNode* tmp = q->head;
		q->head = q->head->next;
		free(tmp);
	}
	free(q->head);
	q->head = q->tail = NULL;
}

void QPush(Queue* q, QDataType x)
{
	assert(q);
	assert(q->head);
	if (!QEmpty(q))
	{
		QNode* newnode = (QNode*)malloc(sizeof(QNode));
		if (newnode == NULL)
		{
			perror("malloc error");
		}
		q->tail->next = newnode;
		q->tail = q->tail->next;
	}
	q->tail->data = x;
	q->tail->next = NULL;
	q->size++;
}

void QPop(Queue* q)
{
	assert(q);
	assert(!QEmpty(q));
	if (q->size > 1)
	{
		QNode* tmp = q->head;
		q->head = q->head->next;
		free(tmp);
		tmp = NULL;
	}
	q->size--;
}

QDataType Qfront(Queue* q)
{
	assert(q);
	assert(!QEmpty(q));
	return q->head->data;
}
QDataType Qback(Queue*q)
{
	assert(q);
	assert(!QEmpty(q));
	return q->tail->data;
}
QDataType QSize(Queue*q)
{
	assert(q);
	assert(!QEmpty(q));
	return q->size;
}
bool QEmpty(Queue* q)
{
	assert(q);
	return !q->size;
}